import dotenv from 'dotenv';
import { rechargeService } from '../src/services/rechargeService';
import { telegramService } from '../src/services/telegramService';
import { RechargeStatus } from '@prisma/client';
import { prisma } from '../src/db';

// 加载环境变量
dotenv.config();

/**
 * 测试完整的充值->支付成功->Telegram通知流程
 */
async function testRechargeToTelegramFlow() {
  console.log('🧪 开始测试完整的充值->支付成功->Telegram通知流程...\n');

  try {
    // 1. 检查Telegram配置
    console.log('1. 检查Telegram配置:');
    const isConfigured = telegramService.isConfigured();
    console.log(`   - 配置状态: ${isConfigured ? '✅ 已配置' : '❌ 未配置'}`);

    if (!isConfigured) {
      console.log('   ⚠️  请配置TELEGRAM_CHAT_ID环境变量后重试');
      console.log('   📝 获取方法：创建群组，添加Bot为管理员，发消息给@JsonDumpBot获取chat_id');
      return;
    }

    // 2. 创建模拟充值订单
    console.log('\n2. 创建模拟充值订单:');
    const mockOrderData = {
      userId: 26814066,
      amount: 11, // 50M金币 * 5.5泰铢
      paymentChannel: 'TOPPAY' as any,
      paymentMethod: 'qrPay' as any,
      createdByUserId: null,
      createdByName: '测试用户自助充值',
      transAccNo: '1234567890123456',
      paymentName: '测试用户',
      bankCode: '001',
      customerEmail: 'test@example.com',
      customerPhone: '+66123456789',
      extendParam: 'SessionId: TEST_SESSION_' + Date.now()
    };

    const createResult = await rechargeService.createRechargeOrder(mockOrderData);
    const orderId = createResult.rechargeRecord.orderId;
    console.log(`   - 订单创建成功: ${orderId}`);
    console.log(`   - 用户ID: ${mockOrderData.userId}`);
    console.log(`   - 金额: ${mockOrderData.amount} THB`);

    // 3. 模拟支付成功（直接更新订单状态）
    console.log('\n3. 模拟支付成功:');
    await prisma.rechargeRecord.update({
      where: { orderId },
      data: {
        status: RechargeStatus.COMPLETED,
        platOrderNum: 'MOCK_PLAT_' + Date.now(),
        payFee: 5.50,
        updatedAt: new Date()
      }
    });
    console.log(`   - 订单状态已更新为: COMPLETED`);

    // 4. 模拟前端调用Telegram通知接口
    console.log('\n4. 发送Telegram通知:');

    // 获取更新后的订单信息
    const updatedRecord = await rechargeService.getRechargeRecordByOrderId(orderId);
    if (!updatedRecord) {
      throw new Error('订单不存在');
    }

    // 发送Telegram通知
    const telegramData = {
      orderId: updatedRecord.orderId,
      amount: parseFloat(updatedRecord.amount.toString()),
      userId: updatedRecord.userId,
      paymentChannel: updatedRecord.paymentChannel,
      status: 'COMPLETED' as any,
      timestamp: updatedRecord.updatedAt || updatedRecord.createdAt,
      merchantId: process.env.TELEGRAM_MERCHANT_ID || 'DL79175852939219'
    };

    const telegramSent = await telegramService.sendRechargeNotification(telegramData);

    if (telegramSent) {
      console.log('   ✅ Telegram通知发送成功!');
      console.log(`   📋 订单号: ${orderId}`);
      console.log(`   💰 金额: ${telegramData.amount} THB`);
      console.log(`   👤 用户ID: ${telegramData.userId}`);
      console.log(`   🏪 商户ID: ${telegramData.merchantId}`);
    } else {
      console.log('   ❌ Telegram通知发送失败');
    }

    // 5. 清理测试数据（可选）
    console.log('\n5. 清理测试数据:');
    await prisma.rechargeRecord.delete({
      where: { orderId }
    });
    console.log(`   - 测试订单已删除: ${orderId}`);

    console.log('\n🎉 完整流程测试完成!');

  } catch (error) {
    console.error('\n❌ 测试过程中发生错误:', error);

    // 如果有错误，尝试清理可能残留的测试数据
    try {
      const testOrders = await prisma.rechargeRecord.findMany({
        where: {
          userId: 26814066,
          createdByName: '测试用户自助充值'
        }
      });

      if (testOrders.length > 0) {
        await prisma.rechargeRecord.deleteMany({
          where: {
            userId: 26814066,
            createdByName: '测试用户自助充值'
          }
        });
        console.log(`\n🧹 已清理 ${testOrders.length} 个测试订单`);
      }
    } catch (cleanupError) {
      console.error('清理测试数据失败:', cleanupError);
    }
  }
}

// 运行测试
testRechargeToTelegramFlow().catch(console.error);